import { defineStore } from 'pinia';
import { getCurrentUserInfo, LoginData } from '@/api/user';
import {
  setToken,
  clearToken,
  setUser,
  getUserId,
  clearUser,
} from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { getUserInfo, LoginDTO, useDetail, useDetailByToken, userLogin } from "@/api/subsidy";
import { UserInfo } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): UserInfo => ({
    portalAuths: [],
    menus: [],
    user: {},
  }),
  getters: {
    userInfo(state: UserInfo): UserInfo {
      return { ...state };
    },
  },

  actions: {
    // Set user's information
    setInfo(partial: Partial<UserInfo>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },
    // Get user's information
    async info() {
      const id = getUserId();
      const res = await useDetail(id as string);
      const tempUser: UserInfo = {
        menus: res.data.menuIds,
        user: res.data,
      };
      this.setInfo(tempUser);
    },

    // Login
    async login(loginForm: LoginDTO) {
      try {
        const res = await userLogin(loginForm);
        if (res.data.authorization) {
          setToken(res.data.authorization);
          const res1 = await useDetailByToken();
          const result = await useDetail(res1.data.id);
          setUser(result.data.id)
          const tempUser: UserInfo = {
            menus: result.data.menuIds,
            user: result.data,
          };
          this.setInfo(tempUser);
        }
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearUser();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },

    // Logout
    async logout() {
      this.logoutCallBack();
    },
  },
});

export default useUserStore;
